package com.lg.common.utils

import android.annotation.SuppressLint
import android.content.Context
import android.content.SharedPreferences
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

class Preference <T>(val name:String , val value:T) : ReadWriteProperty<Any?,T>{

    companion object{
        lateinit var preferences: SharedPreferences

        fun setContext(mContext : Context){
            preferences = mContext.getSharedPreferences(mContext.opPackageName+ApplicationConstants.sharePreferenceName,Context.MODE_PRIVATE)

        }

        fun clear() {
            preferences.edit().clear().apply()
        }
    }



    override fun getValue(thisRef: Any?, property: KProperty<*>): T = getPreference(name, value)


    override fun setValue(thisRef: Any?, property: KProperty<*>, value: T)=putPreference(name, value)

    fun <U> getPreference( name: String ,   value: U) :U = with(preferences){
                    val res:Any = when (value){
                        is Long ->getLong(name,value)
                        is String -> getString(name, value)
                        is Int -> getInt(name, value)
                        is Boolean -> getBoolean(name, value)
                        is Float -> getFloat(name, value)
                        else -> throw IllegalArgumentException("This type can be saved into Preferences")
                    }!!
        res as U
    }



    fun <U> putPreference( name: String ,   value: U)= with(preferences.edit()){
        when (value){
            is Long -> putLong(name, value)
            is String -> putString(name, value)
            is Int -> putInt(name, value)
            is Boolean -> putBoolean(name, value)
            is Float -> putFloat(name, value)
            else -> throw IllegalArgumentException("This type can be saved into Preferences")
        }.apply()
    }
}